/**
 * 文件：activity_control_select.java
 * 包名：com.ronri.ams.sample;   --- 正式发布时需要修正
 * 说明：单选择
 * 作者：MS During
 * 日期：2017/5/10
 * 历史：
 */
package com.ronri.ams.sample;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.cz.nongyetongv5.R;
import com.ronri.db.RemoteDataService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class activity_control_select extends abstract_activity {
    // 列表控件
    private ListView mListView = null;

    // List适配器
    private ChoiceView adapter = null;

    // 数据源
    private List<Map<String, Object>> mItems = new ArrayList<Map<String, Object>>();

    // 远程服务器地址
    private String mRemoteAddress = null;

    // 关键字名
    private String mKeyName = "key";

    private String mJson = "";

    // 获取标题名称
    private String mKeyTitleName = "";

    // 选择的行信息
    private List<Integer> mSelectItems = new ArrayList<Integer>();

    // 远程数据
    private RemoteDataService mRemoteDB = new RemoteDataService();

    // 选择模式
    private int mSelectMode = ListView.CHOICE_MODE_SINGLE;

    private int mSelectLine = 0;

    private CheckableFrameLayout lastCheckedOption = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.contorl_single_select);
        Log.i("aaa","activity_control_select");
        Bundle bundle = getIntent().getExtras();

        // 设置选择模式
        mSelectMode = bundle.getInt("selectMode");

        // 获取远程地址信息
        mRemoteAddress = bundle.getString("remoteAddress");
        mKeyName = bundle.getString("filterKeyName");
        mKeyTitleName = bundle.getString("viewTitleName");

        String szTitle = bundle.getString("title");
        String szvTitle = bundle.getString("vtitle");

        int nSelectMode = bundle.getInt("selectMode", ListView.CHOICE_MODE_SINGLE);
        mJson = bundle.getString("data");

        // 显示标题与右边功能
        setTitle(szTitle, szvTitle);

        // 初始化内容
        init();
        String mSelectValue = bundle.getString("value");

        mListView = (ListView)findViewById(R.id.lvDataItem);
        mListView.setChoiceMode(mSelectMode);// 选择模式

        LoadData(mJson, mSelectValue);
        mSelectItems.add(0);
    }

    /***
     * 确认返回
     * @return
     */
    @Override
    public boolean SureReturn() {
        String szSplit = "";
        String szResult = "";

        szResult = "";
        for(Integer iTem : mSelectItems){
            Map<String, Object> map = mItems.get(iTem);
            String szJson = (String)map.get("selectValue");
            szResult = szResult + szSplit + szJson;
            szSplit = ",";
        }

        if (szResult != "") {
            Intent intent = new Intent();
            Bundle bundle = new Bundle();
            bundle.putString("returnValue", "[" + szResult + "]");

            intent.putExtras(bundle);

            setResult(RESULT_OK, intent);
        } else {
            setResult(RESULT_CANCELED);
        }

        // 释放内存
        adapter.notifyDataSetChanged();
        mListView = null;
        mSelectItems.clear();
        mItems.clear();

        return super.SureReturn();
    }

    /***
     * 装载数据
     * @param szJson
     * @return
     */
    public int LoadData(String szJson, String szSelect) {
        if (szJson == null)
            return -1;

        String Select[] = {};

        if (szSelect != null)
            Select = szSelect.split(",");

        JSONArray rows = JSONArray.parseArray(szJson);

        for (int i = 0; i < rows.size(); i++) {
            JSONObject iTem = rows.getJSONObject(i);

            boolean bSelect = false;
            if (mKeyTitleName != "") {
                if (iTem.containsKey(mKeyTitleName)) {
                    // 获取Title值
                    String szTitle = iTem.getString(mKeyTitleName);
                    String szValue = iTem.getString(mKeyName);

                    // 转换成JSON数据
                    String szJsonString = iTem.toJSONString();

                    Map<String, Object> iTemData = new HashMap<String, Object>();

                    iTemData.put("listTitle", szTitle);
                    iTemData.put("selectValue", szJsonString);

                    for(String ii : Select){
                        if (ii.equals(szValue)){
                            mSelectLine = i;
                            bSelect = true;
                            break;
                        }
                    }
                    iTemData.put("selected", bSelect);

//                    if(bSelect){
//                        mSelectItems.clear();
//                        mSelectItems.add(iTemData);
//                    }
                    mItems.add(iTemData);
                }
            }
        }

        // 刷新数据
//        if (mListView != null) {
//            ChoiceView adapter = new ChoiceView(activity_control_single_select.this, mItems);
//            mListView.setAdapter(adapter);
//            mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//                @Override
//                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                    //获取条目
//                    CheckableFrameLayout linearLayout = (CheckableFrameLayout) view.findViewById(R.id.ll_contain);
//                    if (linearLayout.isChecked()) {
//                        if(!mSelectItems.contains(i)){
//                            mSelectItems.add(i);
//                        }
//                    } else {
//                        if (mSelectItems.contains(i)){
//                            mSelectItems.remove(i);
//                        }
//                    }
//                }
//            });
//
//            // 选择模式
//            mListView.setChoiceMode(mSelectMode);
//            mListView.setAdapter(adapter);
//        }
        adapter = new ChoiceView(activity_control_select.this, mItems);

        mListView.setAdapter(adapter);

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                //获取条目
                lastCheckedOption = (CheckableFrameLayout) view.findViewById(R.id.ll_contain);
                if (lastCheckedOption.isChecked()) {
                    mSelectItems.clear();
                    mSelectItems.add(i);
//
//                    if(!mSelectItems.contains(i)){
//                        mSelectItems.add(i);
//                    }
                } else {
                    if (mSelectItems.contains(i)){
                        mSelectItems.remove(i);
                    }
                }
            }
        });

        mListView.post(new Runnable() {
            @Override
            public void run() {
                lastCheckedOption = (CheckableFrameLayout)mListView.getChildAt(mSelectLine).findViewById(R.id.ll_contain);
                lastCheckedOption.setVisibility(View.VISIBLE);
                mListView.setItemChecked(mSelectLine, true);
            }
        });


        return  -1;
    }
    /***
     * 获取指定页面数据
     * @param nPageIndex
     * @return
     */
    private int getPageData(int nPageIndex) {

        /**组合参数*/
        Map<String, Object> iTem = new HashMap<String, Object>();

        // 设置参数
        String szParamets = MergeRemoteParamerts(0, 10, iTem);

        // 获取远程数据
        mRemoteDB.getRemoteData(mRemoteAddress, szParamets, "POST", new RemoteDataService.OnRemoteDataEvent() {
            /***
             * 返回结果
             *
             * @param szString
             */
            @Override
            public void OnResultEvent(String szString) {
                try {
                    // 转换成JSON处理
                    JSONObject json = JSON.parseObject(szString);

                    if (json.containsKey("code")) {
                        int nCode = json.getInteger("code");
                        if (nCode == 0) {
                            JSONObject data = json.getJSONObject("data");
                            JSONArray rows = data.getJSONArray("rows");

                            for (int i = 0; i < rows.size(); i++) {
                                JSONObject iTem = rows.getJSONObject(i);

                                if (mKeyTitleName != "") {
                                    if (iTem.containsKey(mKeyTitleName)) {
                                        // 获取Title值
                                        String szTitle = iTem.getString(mKeyTitleName);

                                        // 转换成JSON数据
                                        String szJsonString = iTem.toJSONString();

                                        Map<String, Object> iTemData = new HashMap<String, Object>();

                                        iTemData.put("listTitle", szTitle);
                                        iTemData.put(szTitle, szJsonString);

                                        mItems.add(iTemData);
                                    }
                                }
                            }
//
//                            // 刷新数据
//                            if (mListView != null) {
//                                ListAdapter adapter = new ArrayAdapter<Map<String,Object>>(activity_control_select.this,
//                                        R.layout.v_default_single_select, mItems) {
//                                    @Override
//                                    public View getView(int position, View convertView, ViewGroup parent) {
//                                        final ChoiceView view;
//                                        if(convertView == null) {
//                                            view = new ChoiceView(activity_control_select.this);
//                                        } else {
//                                            view = (ChoiceView)convertView;
//                                        }
//
//                                        // 获取数据
//                                        Map<String,Object> iTem = getItem(position);
//
//                                        if (mKeyTitleName != "") {
//                                            if (iTem.containsKey("listTitle")) {
//                                                for (Map.Entry<String, Object> entry : iTem.entrySet()) {
//                                                    if(entry.getKey() == "listTitle"){
//                                                        view.setText(entry.getValue().toString());
//                                                        view.setTag(iTem);
//                                                        return view;
//                                                    }
//                                                }
//                                            }
//                                        }
//
//                                        return view;
//                                    }
//                                };
//
//                                mListView.setAdapter(adapter);
                            ChoiceView adapter = new ChoiceView(activity_control_select.this, mItems);
                            mListView.setAdapter(adapter);
                            mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                    //获取条目
                                    CheckableFrameLayout linearLayout = (CheckableFrameLayout) view.findViewById(R.id.ll_contain);
                                    if (linearLayout.isChecked()) {
                                    } else {
                                    }
                                }
                            });
                        }
                    }
                } catch (JSONException ex) {

                }
            }

            /***
             * 进度展示
             *
             * @param nStatus
             */
            @Override
            public void OnRuningState(int nStatus) {
                // 显示进度条
            }

            /***
             * 回调获取参数
             *
             * @return
             */
            @Override
            public String OnGetCustomParam() {


                return null;
            }
        });

        return 0;
    }
}
